<?php 
/**                                          
 * 用户标签
 * @author M2
 * @version 1.0
 * create Date 2013-04-27
 */
class UserTagModel extends Model{
	/**
	 * 查找指定签标的用户	
	 * @param string $k 标签
	 */
	function doSearchTag($k) {
		global $yl;
		$keyinfo = M('tag')->where("tag_name='{$k}'")->find();
		if ($keyinfo && $k ) {
			$list = $this->where("tag_id=".$keyinfo['tag_id'])->field('uid')->findPage();
			$uids = common('Array')->getSubByKey($list['data'], 'uid');
			//缓存用户的资料, 粉丝数, 关注数, Tag列表
			$user_model 	  = model('User');
			$user_count_model = model('UserCount');
			$user_model->setUserObjectCache($uids);
			$user_count_model->setUserFollowerCount($uids);
			$user_count_model->setUserFollowingCount($uids);
			$this->setUserTagObjectCache($uids);
			foreach ($list['data'] as $k => $v) {
				$list['data'][$k]['user']        = $user_model->getUserByIdentifier($v['uid']);
				$list['data'][$k]['taglist'] 	 = $this->getUserTagList($v['uid']);
				$list['data'][$k]['following']   = $user_count_model->getUserFollowingCount($v['uid']);
				$list['data'][$k]['follower']    = $user_count_model->getUserFollowerCount($v['uid']);
				$list['data'][$k]['followState'] = model('UserPrivacy')->getFollowState( $yl['user']['uid'] , $v['uid'] );
			}
		}else {
			$list['count'] = 0;
		}
		return $list;
	}
	
	
	/**
	 * 设置缓存标签	
	 * @param array $uids
	 */
	public function setUserTagObjectCache(array $uids){
		if (!is_numeric($uids[0]))
			return false;
		$base_cache_id = 'user_tag_';
		$uids = implode(',', $uids);
		$sql  = "SELECT a.*,b.tag_name FROM {$this->tablePrefix}user_tag a LEFT JOIN {$this->tablePrefix}tag b ON b.tag_id=a.tag_id WHERE a.uid IN ( {$uids} ) ORDER BY a.user_tag_id ASC";
		$res  = $this->query($sql);
		// 格式化为: array($uid => $tags_array)
		// 注: 每人最多含有10个标签
		$user_tags = array();
		foreach ($res as $v) {
			if (count($user_tags[$v['uid']]) >= 10)
				continue;
			else
				$user_tags[$v['uid']][] = $v;
		}
		foreach ($user_tags as $k => $v)
			S($base_cache_id . $k, $v);
		return $res;
	}
	
	/**
	 * 获取用户Tag列表	
	 * @param int $uid
	 */
	public function getUserTagList($uid){
		$base_cache_id = 'user_tag_';
		if (($res = S($base_cache_id . $uid)) === false) {
			$this->setUserTagObjectCache(array($uid));
			$res  = S($base_cache_id . $uid);
		}
		return $res;
	}
}
?>